package com.byzk.p2p.admin.user.service;

import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.borrow.dao.TenderDao;
import com.byzk.p2p.admin.borrow.vo.ChangeAwaitVo;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.dao.BorrowPaymentDetailDao;
import com.byzk.p2p.admin.money.dao.FundRecordDao;
import com.byzk.p2p.admin.money.dto.FundRecord;
import com.byzk.p2p.admin.money.dto.RechargeRecord;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.system.dao.CallbackDao;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.user.dao.UserAccountDao;
import com.byzk.p2p.admin.user.dao.UserDao;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.vo.UserAccountVo;
/**
 * 用户资金操作层		
 * @author suker.zhou
 *
 */
@Service
public class UserAccountService {

	
	@Autowired
	private UserAccountDao userAccountDao;
	@Autowired
	private TenderDao tenderDao;
	@Autowired
	private UserAccountDao accountDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private FundRecordDao fundDao;
	@Autowired
	private CallbackDao callbackDao;
	@Autowired
	private BorrowPaymentDetailDao borrowPaymentDetailDao;
	
	/**
	 * 查询用户资金记录
	 * @param index
	 * @param limit
	 * @param vo
	 * @return
	 */
	public PageInfo<UserAccountVo> listAll(UserAccountVo vo){
		int count=userAccountDao.count(vo);
		List<UserAccountVo> voList=userAccountDao.list(vo);
		for (UserAccountVo userAccountVo : voList) {
			Integer userId=userAccountVo.getUserId();
			ChangeAwaitVo await=tenderDao.sumChangeAwait(userId,null);
			//待收总额
			UserAccount account=accountDao.getByUserId(userId);
			userAccountVo.setAwait(tenderDao.sumAwaitTotal(userId)+await.getPaymentTotal()+account.getAwait());
		}
		PageInfo<UserAccountVo> page=new PageInfo<UserAccountVo>(count, vo.getIndex() , vo.getLimit());
		page.setPageList(voList);
		return page;
	}

	public UserAccountVo getAccountVoByUserId(Integer userId){
		ChangeAwaitVo await=tenderDao.sumChangeAwait(userId,null);
		//待收总额
		UserAccount temp=accountDao.getByUserId(userId);
		UserAccountVo account=userAccountDao.selectByUserId(userId);
		account.setAwait(tenderDao.sumAwaitTotal(userId)+await.getPaymentTotal()+temp.getAwait());
		return account;
	}
	
	public Integer saveOrUpdate(UserAccount userAccount){
		if(userAccount.getId()==null){
			return userAccountDao.insert(userAccount);
		}else{
			return userAccountDao.update(userAccount);
		}
	}
	
	
	public UserAccount getByUserId(Integer uid){
		return userAccountDao.getByUserId(uid);
	}
	
	/**
	 * 更新用户账户信息
	 * @param userId 用户id
	 * @param amount 数额
	 * @param type 0为减少，1为增加
	 * @return
	 */
	public Integer updateUserAccount(Integer userId,Double amount,int type){
		UserAccount account=userAccountDao.getByUserId(userId);
		if(type==0){
			account.setBalance(account.getBalance()-amount);
			account.setTotalAmount(account.getTotalAmount()-amount);
			account.setTotalExpenses(account.getTotalExpenses()-amount);
		}else{
			account.setBalance(account.getBalance()+amount);
			account.setTotalAmount(account.getTotalAmount()+amount);
			account.setTotalIncome(account.getTotalIncome()+amount);
//			account.setNotUsedMoney(account.getNotUsedMoney()+amount);
		}
		return userAccountDao.update(account);
	}
	
	public Double sumTotalRecharge(RechargeRecord record){
		return userAccountDao.sumTotalRecharge(record);
	}

	public UserAccount sumUserAccount() {
		return userAccountDao.sumUserAccount();
	}
	
	public UserAccountVo selectAccountVoByUserId(Integer userId){
		UserAccountVo account=userAccountDao.selectByUserId(userId);
		return account;
	}
	
	/**
	 * 根据用户ID删除用户账户
	 */
	public int deleteByUserId(Integer userId) {
		return accountDao.deleteByUserId(userId);
	}
	
	/**
	 * 根据用户id查询用户账户
	 */
	public UserAccount getAccount(Integer id) {
		return accountDao.getAccount(id);
	}
	
	public String addPercent(Integer userId,Double amount) {
		User user=userDao.getById(userId);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(Config.user_id);
		dto.setIn_cust_no(user.getPhone());
		dto.setContract_no("");
		dto.setRem("加息奖励");
		double amt = BaseUtil.StringToDoubletoFixed2(amount*100);
		dto.setAmt((int)(amt)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));
		
		String backStr;
		try {
			backStr = WebUtils.sendHttp(Config.paltform_to_user_url,dto);
			System.out.println(backStr);
			
			Callback callback=new Callback("平台向用户转账",backStr,new Date());
			callbackDao.insert(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				UserAccount account=accountDao.getByUserId(userId);
				account.setBalance(account.getBalance()+amount);
				account.setTotalAmount(account.getTotalAmount()+amount);
				
				
				FundRecord fund=new FundRecord();
				fund.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
				fund.setCreateTime(new Date());
				fund.setRemark("加息奖励");
				fund.setType(FundRecordType.Type.ADD_PERCENT.index);
				fund.setUserId(userId);
				fund.setIncome(amount);
				fund.setExpend(0.0);
				fund.setTerminal("PC");
				fund.setFreezen(0.0);
				fund.setBalance(account.getBalance());

				fundDao.insert(fund);
				accountDao.update(account);
				System.out.println();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 待领奖金变现
	 */
	public String takeBonus(Integer userId, Double amount, String levelName) {
		User user=userDao.getById(userId);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(Config.user_id);
		dto.setIn_cust_no(user.getPhone());
		dto.setContract_no("");
		dto.setRem("邀请"+user.getPhone()+"达到"+levelName+"待领变现");
		double amt = BaseUtil.StringToDoubletoFixed2(amount*100);
		dto.setAmt((int)(amt)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));
		
		String backStr;
		try {
			backStr = WebUtils.sendHttp(Config.paltform_to_user_url,dto);
			System.out.println(backStr);
			
			Callback callback=new Callback("平台向用户转账",backStr,new Date());
			callbackDao.insert(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				UserAccount account=accountDao.getByUserId(userId);
				account.setBalance(account.getBalance()+amount);
				account.setTotalAmount(account.getTotalAmount()+amount);
				account.setStayAmount(account.getStayAmount()-amount);//扣除待领奖金
				
				//资金明细
				FundRecord fund=new FundRecord();
				fund.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
				fund.setCreateTime(new Date());
				fund.setRemark("邀请"+user.getPhone()+"达到"+levelName+"待领变现");
				fund.setType(FundRecordType.Type.STAY_MONEY.index);
				fund.setUserId(userId);
				fund.setIncome(amount);
				fund.setExpend(0.0);
				fund.setTerminal("PC");
				fund.setFreezen(0.0);
				fund.setBalance(account.getBalance());

				fundDao.insert(fund);
				accountDao.update(account);
				System.out.println("待领奖金领取=============="+user.getUsername()+"|收益："+amount);
			}
			return resp_code;
		} catch (Exception e) {
			System.out.println("报错==============");
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 可用余额同步
	 */
	public String updateBalance(Integer userId, Double amount) {
		User user=userDao.getById(userId);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(Config.user_id);
		dto.setIn_cust_no(user.getPhone());
		dto.setContract_no("");
		dto.setRem("同步金账户可用余额");
		double amt = BaseUtil.StringToDoubletoFixed2(amount*100);
		dto.setAmt((int)(amt)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));
		
		String backStr;
		try {
			backStr = WebUtils.sendHttp(Config.paltform_to_user_url,dto);
			System.out.println(backStr);
			
			Callback callback=new Callback("平台向用户转账",backStr,new Date());
			callbackDao.insert(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				
				//资金明细
				FundRecord fund=new FundRecord();
				fund.setCode(BaseUtil.generateCode(BaseUtil.ZIJINLIUSHUI));
				fund.setCreateTime(new Date());
				fund.setRemark("同步金账户可用余额");
				fund.setType(FundRecordType.Type.OTHER.index);
				fund.setUserId(userId);
				fund.setIncome(0.0);
				fund.setExpend(0.0);
				fund.setTerminal("PC");
				fund.setFreezen(0.0);
				fund.setBalance(amount);

				fundDao.insert(fund);
				System.out.println("同步金账户可用余额=============="+user.getUsername()+"|同步金额："+amount);
			}
			return resp_code;
		} catch (Exception e) {
			System.out.println("报错==============");
			e.printStackTrace();
		}
		return null;
	}
	

	/**
	 * 查找钻石和金钻用户
	 * @return
	 */
	public List<UserAccount> getAccountLevel5Or6(){
		return userAccountDao.getAccountLevel5Or6();
	}
	
	/**
	 * 获取代收资本金
	 * @param userId
	 * @return
	 */
	public Double sumAwaitFundByUserId(Integer userId) {
		return borrowPaymentDetailDao.sumAwaitFundByUserId(userId);
	}
	
	/**
	 * 获取代收利息
	 * @param userId
	 * @return
	 */
	public Double sumAwaitInterestByUserId(Integer userId) {
		return borrowPaymentDetailDao.sumAwaitInterestByUserId(userId);
	}
}
